<template>
  <n-form>
    <div class="choose-branch-page">
      <n-grid :cols="24" :x-gap="10" :y-gap="10">
        <n-gi :offset="8" :span="8">
          <div class="text-xl font-semibold mb-5">选择店铺</div>
        </n-gi>
        <n-gi :offset="8" :span="8">
          <n-form-item :show-label="false" path="branchId">
            <n-select
              v-model:value="branchId"
              value-field="id"
              label-field="name"
              clearable
              :options="userStore.ownBranches"
              :loading="loading"
              placeholder="请选择要登入的店铺"
            />
          </n-form-item>
        </n-gi>
        <n-gi :offset="8" :span="8">
          <n-button
            :disabled="!branchId"
            :loading="loading"
            type="primary"
            block
            @click.stop="handleChangeBranch"
            >确认</n-button
          >
        </n-gi>
      </n-grid>
    </div>
  </n-form>
</template>
<script setup lang="ts">
import { ref, onMounted } from "vue";
import { get, isEmpty } from "lodash-es";
import { useRouter, useRoute } from "vue-router";
import { changeBranch } from "@/api/branches/branches.api";
import { useUserStore } from "@/store/modules/user.store";
import * as RouterNames from "@/router/routerNames/index";

const router = useRouter();
const route = useRoute();
const userStore = useUserStore();
const loading = ref<boolean>(false);
const branchId = ref<string | undefined>(undefined);

const handleChangeBranch = async () => {
  if (branchId.value) {
    try {
      loading.value = true;
      const res = await changeBranch(branchId.value);
      const currentBranch = get(res, "result") || {};
      if (!isEmpty(currentBranch)) {
        userStore.changeCurrentBranch(currentBranch);
        const redirect = get(route, "query.redirect") || "";
        if (
          redirect &&
          ![
            RouterNames.LOGIN_PAGE.URL,
            RouterNames.CHOOSE_BRANCH_PAGE.URL,
          ].includes(redirect as string)
        ) {
          router.push({
            path: redirect as string,
            replace: true,
          });
        } else {
          router.push({
            name: RouterNames.DASHBOARD_PAGE.NAME,
            replace: true,
          });
        }
      }
    } finally {
      loading.value = false;
    }
  }
};

const init = async () => {
  const currentBranch = userStore.currentBranch;
  if (!isEmpty(currentBranch)) {
    const currentBranchId = get(currentBranch, "id") || "";
    branchId.value = currentBranchId;
  }
};

onMounted(() => {
  init();
});
</script>
<style lang="scss" scoped>
@import "./index.scss";
</style>
